package main;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Scanner;

import InterDomain.InterRouter;
import IntraDomain.IntraRouter;
import Objects.Config;
import Objects.Logger;
import Objects.Parser;
import Objects.Router;

public class Main {
	public static void main(String[] args) {
		if (args.length != 2) {
			System.err.println("Usage: java -jar DV.jar [configuration file name] [router ID of this node]");
			System.exit(1);
		}

		String fileName = args[0];
		String routerID = args[1];

		Parser parser = new Parser();
		// has to set my router ID before reading in the config file
		String myIP = "";
		try {
			InetAddress ip = InetAddress.getLocalHost();
			myIP = ip.getHostAddress();
		} catch (Exception e) {
			e.printStackTrace();
		}
		// System.out.println(myIP);
		parser.setMyRouterID(routerID);
		parser.readConfigFile(fileName);
		Config myConfig = parser.getMyConfig();
		myConfig.setIP(myIP);
		parser.setMyConfig(myConfig);
		Parser.mapFileName = "map.txt";
		parser.writeFile();
		parser.readMapFile();

		// System.out.println(parser.getMyConfig());
		// System.out.println(parser.getMyNeighbors());

		Router.myConfig = parser.getMyConfig();
		Router.myNeighbors = parser.getMyNeighbors();
		Router.init();

		if (Router.myConfig.getIG() == 'i') {
			IntraRouter ir = new IntraRouter();
			ir.start();
		} else {
			InterRouter ir = new InterRouter();
			ir.start();
		}

		Logger.log(Logger.DEBUG, IntraRouter.myNeighbors.printList());
		Scanner sc = new Scanner(System.in);
		Logger.log(Logger.ALL, "Router " + routerID + " started");
		
		while (true) {
			Logger.log(Logger.ALL, "Menu:");
			Logger.log(Logger.ALL, "1. Print routing table");
			Logger.log(Logger.ALL, "2. Send message");
			Logger.log(Logger.ALL, "3. Toggle debug messages");

			int choice = sc.nextInt();
			String message = "";
			String destinationRouter = "";
			if (choice == 1) {
				Router.printRoutingTable();
			} else if (choice == 2) {
				ArrayList<String> des = Router.getReachableDestination();
				Logger.log(Logger.ALL, "Pick the router to send message: ");
				int i = 0;
				for (i = 0; i < des.size(); i++) {
					Logger.log(Logger.ALL, (i + 1) + ": " + des.get(i));
				}
				Logger.log(Logger.ALL, (i + 1) + ": Other");
				int desNode = sc.nextInt();
				sc.nextLine();
				if (desNode == i + 1) {
					Logger.log(Logger.ALL, "Enter the destination node: ");
					String destinationNode = sc.nextLine().trim();
					Logger.log(Logger.ALL, "Message: ");
					message = sc.nextLine();
					Router.sendDataMessage(routerID, destinationNode, message);
				} else {
					destinationRouter = des.get(desNode - 1);
					Logger.log(Logger.ALL, "Message: ");
					message = sc.nextLine();
					Router.sendDataMessage(routerID, destinationRouter, message);
				}
			} else if (choice == 3) {
				if (Logger.debug == false)
					Logger.debug = true;
				else
					Logger.debug = false;
			}
		}
	}
}
